import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:magma/heartbeat/helpers/magma_toast.dart';
import 'package:magma/heartbeat/parts/magma_report_dialog.dart';
import 'package:magma/heartbeat/parts/login_required_dialog.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/blueprint/event_model.dart';
import '../../comms_link/app_state.dart';

/// 活动详情视图模型
class EventDetailNavigatorViewModel extends ReactiveViewModel {
  GatheringModel? _currentEvent;
  List<GatheringCommentModel> _comments = [];

  /// 获取当前活动
  GatheringModel? get currentEvent => _currentEvent;

  /// 获取活动评论列表
  List<GatheringCommentModel> get comments => _comments;

  /// 初始化活动详情数据
  void initializeEventDetail(String eventId) {
    _currentEvent = appState.gatheringOrganizer.gatherings.firstWhere(
      (event) => event.id == eventId,
      orElse: () => throw Exception('Event not found'),
    );
    _loadEventComments();
    notifyListeners();
  }

  /// 加载活动评论
  void _loadEventComments() {
    _comments = appState.gatheringOrganizer.getCommentsByGatheringId(
      _currentEvent?.id ?? '',
    );
  }

  /// 删除评论
  void deleteComment(String commentId) {
    _comments.removeWhere((comment) => comment.id == commentId);
    notifyListeners();
  }

  @override
  List<ReactiveServiceMixin> get reactiveServices => [];
}

/// 活动详情页面
class EventDetailStory extends StatefulWidget {
  final String eventId;

  const EventDetailStory({super.key, required this.eventId});

  @override
  State<EventDetailStory> createState() => _EventDetailStoryState();
}

class _EventDetailStoryState extends State<EventDetailStory> {
  late ScrollController _firstRowController;
  late ScrollController _secondRowController;

  @override
  void initState() {
    super.initState();
    _firstRowController = ScrollController();
    _secondRowController = ScrollController();

    // 页面加载后让第二排滚动半条评论长度
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollSecondRowHalf();
    });
  }

  @override
  void dispose() {
    _firstRowController.dispose();
    _secondRowController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<EventDetailNavigatorViewModel>.reactive(
      viewModelBuilder:
          () =>
              EventDetailNavigatorViewModel()
                ..initializeEventDetail(widget.eventId),
      builder: (context, viewModel, child) {
        if (viewModel.currentEvent == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'Event not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Stack(
            children: [
              // 主要内容
              SingleChildScrollView(
                child: Column(
                  children: [
                    // 头部图片区域
                    _renderHeaderImage(viewModel.currentEvent!),
                    // 内容区域
                    _renderContentArea(viewModel),
                    // 底部留白，避免被底部按钮遮挡
                    SizedBox(height: 80.h),
                  ],
                ),
              ),
              // 固定标题栏
              _constructNavigationBar(context),
              // 底部报名按钮
              _assembleSignUpButton(context),
            ],
          ),
        );
      },
    );
  }

  /// 构建导航栏
  Widget _constructNavigationBar(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        bottom: false,
        child: Container(
          padding: EdgeInsets.only(
            left: 16.w,
            right: 16.w,
            top: 16.h,
            bottom: 16.h,
          ),
          child: Row(
            children: [
              GestureDetector(
                onTap: () => QR.back(),
                child: Image.asset(
                  MagmaConstant.back,
                  width: 20.w,
                  height: 25.w,
                ),
              ),
              Spacer(),
              Text(
                'Event Details',
              ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
              Spacer(),
              SizedBox(width: 20.w),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建底部报名按钮
  Widget _assembleSignUpButton(BuildContext context) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        top: false,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                MagmaColor.black.withOpacity(0.0),
                MagmaColor.black.withOpacity(0.8),
                MagmaColor.black,
              ],
              stops: [0.0, 0.5, 1.0],
            ),
          ),
          child: GestureDetector(
            onTap: () {
              _handleSignUpTap(context);
            },
            child: Container(
              width: double.infinity,
              height: 56.h,
              decoration: BoxDecoration(
                color: MagmaColor.purple,
                borderRadius: BorderRadius.circular(28.r),
              ),
              child: Center(
                child: Text('Sign Up').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.black,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 处理报名按钮点击
  void _handleSignUpTap(BuildContext context) {
    MagmaToast.success(
      context,
      title: 'Sign up Successful!',
      description: 'We will contact you soon.',
    );
  }

  /// 构建头部图片
  Widget _renderHeaderImage(GatheringModel event) {
    return AspectRatio(
      aspectRatio: 414 / 571,
      child: Stack(
        children: [
          // 活动图片
          Image.asset(
            event.image,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
          // 渐变蒙层
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.transparent,
                  Colors.black.withValues(alpha: 0.3),
                  Colors.black.withValues(alpha: 0.6),
                ],
                stops: [0.0, 0.5, 1.0],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建内容区域
  Widget _renderContentArea(EventDetailNavigatorViewModel viewModel) {
    return Transform.translate(
      offset: Offset(0, -100.h), // 与头部图片重叠
      child: Column(
        children: [
          // 活动详情卡片
          _renderEventDetailCard(viewModel.currentEvent!),
          SizedBox(height: 24.h),
          // 活动信息
          _renderEventInformation(viewModel.currentEvent!),
          SizedBox(height: 24.h),
          // 活动评论
          _renderEventComments(viewModel),
          SizedBox(height: 32.h),
        ],
      ),
    );
  }

  /// 构建活动详情卡片
  Widget _renderEventDetailCard(GatheringModel event) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(MagmaConstant.eventDetailCard),
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(2.r),
      ),
      child: Column(
        children: [
          // 活动标题
          Text(
            event.title,
            textAlign: TextAlign.center,
            style: TextStyle(height: 1.4),
          ).blackHanSans(
            fontSize: 20.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w400,
          ),
          SizedBox(height: 16.h),
          // 虚线分隔符
          _renderDashedLine(),
          SizedBox(height: 16.h),
          // 活动描述
          Text(
            event.description,
            textAlign: TextAlign.left,
            style: TextStyle(height: 1.5),
          ).inter(
            fontSize: 16.sp,
            color: MagmaColor.black.withValues(alpha: 0.6),
            fontWeight: FontWeight.w400,
          ),
        ],
      ),
    );
  }

  /// 构建虚线分隔符
  Widget _renderDashedLine() {
    return SizedBox(
      width: double.infinity,
      height: 1.h,
      child: CustomPaint(painter: DashedLinePainter()),
    );
  }

  /// 构建活动信息
  Widget _renderEventInformation(GatheringModel event) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 活动时间
          _renderInfoRow(
            imagePath: MagmaConstant.clockIcon,
            title:
                '${_formatDate(event.startTime)}-${_formatDate(event.endTime)}',
            subtitle: 'Event Time',
          ),
          SizedBox(height: 16.h),
          // 活动地点
          _renderInfoRow(
            imagePath: MagmaConstant.locationIcon,
            title: event.location,
            subtitle: 'Event location',
          ),
        ],
      ),
    );
  }

  /// 构建信息行
  Widget _renderInfoRow({
    required String imagePath,
    required String title,
    required String subtitle,
  }) {
    return Container(
      child: Row(
        children: [
          Image.asset(imagePath, width: 52.w, height: 52.w),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    height: 1.4,
                    color: Colors.white.withValues(alpha: 0.95),
                    fontSize: 18.sp,
                    fontStyle: FontStyle.italic,
                    fontFamily:
                        GoogleFonts.inter(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  subtitle,
                  style: TextStyle(
                    height: 1.4,
                    color: Colors.white.withValues(alpha: 0.60),
                    fontSize: 12.sp,
                    fontStyle: FontStyle.italic,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建活动评论
  Widget _renderEventComments(EventDetailNavigatorViewModel viewModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 评论标题
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Text('Activity Feedback').blackHanSans(
                fontSize: 18.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w600,
              ),
              Spacer(),
              GestureDetector(
                onTap: () {
                  _handleEditCommentTap(context, viewModel);
                },
                child: Image.asset(
                  MagmaConstant.commentEdit,
                  width: 22.w,
                  height: 22.w,
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 16.h),
        // 评论列表 - 两排显示
        SizedBox(
          height: 140.h, // 调整高度以容纳两排60.h的评论
          child: Column(
            children: [
              // 第一排评论
              SizedBox(
                height: 60.h,
                child: ListView.builder(
                  controller: _firstRowController,
                  scrollDirection: Axis.horizontal,
                  physics: BouncingScrollPhysics(),
                  itemCount: (viewModel.comments.length / 2).ceil(),
                  itemBuilder: (context, index) {
                    if (index * 2 < viewModel.comments.length) {
                      final comment = viewModel.comments[index * 2];
                      return _renderCommentItem(comment, index * 2, viewModel);
                    }
                    return SizedBox.shrink();
                  },
                ),
              ),
              SizedBox(height: 12.h),
              // 第二排评论
              SizedBox(
                height: 60.h,
                child: ListView.builder(
                  controller: _secondRowController,
                  scrollDirection: Axis.horizontal,
                  physics: BouncingScrollPhysics(),
                  itemCount: (viewModel.comments.length / 2).ceil(),
                  itemBuilder: (context, index) {
                    if (index * 2 + 1 < viewModel.comments.length) {
                      final comment = viewModel.comments[index * 2 + 1];
                      return _renderCommentItem(
                        comment,
                        index * 2 + 1,
                        viewModel,
                      );
                    }
                    return SizedBox.shrink();
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建评论项目
  Widget _renderCommentItem(
    GatheringCommentModel comment,
    int index,
    EventDetailNavigatorViewModel viewModel,
  ) {
    // 根据评论的userId获取真实用户信息
    final user = appState.userStore.getUserById(comment.userId);
    final String avatar = user?.avatar ?? MagmaConstant.avatar1; // 默认头像

    return GestureDetector(
      onTap: () {
        _showCommentDetailDialog(context, comment, viewModel);
      },
      child: Container(
        width: 306.w,
        height: 60.h,
        margin: EdgeInsets.only(right: 12.w),
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          color: MagmaColor.green,
          borderRadius: BorderRadius.circular(34.r),
          border: Border.all(color: const Color(0xFF333333), width: 1.w),
        ),
        child: Row(
          children: [
            // 头像
            Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: MagmaColor.black, width: 1.w),
              ),
              child: ClipOval(
                child: Image.asset(
                  avatar,
                  fit: BoxFit.cover,
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
            ),
            SizedBox(width: 8.w),
            // 评论内容
            Expanded(
              child: Text(
                comment.content,
                maxLines: 2, // 最多显示两排
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                textAlign: TextAlign.left,
                style: TextStyle(
                  fontSize: 15.sp,
                  color: MagmaColor.black,
                  fontFamily:
                      GoogleFonts.poetsenOne(
                        fontWeight: FontWeight.w400,
                      ).fontFamily,
                  fontWeight: FontWeight.w500,
                  height: 1.2, // 行高
                ),
              ),
            ),
            SizedBox(width: 8.w),
            // 举报按钮
            GestureDetector(
              onTap: () {
                _showReportDialog(context, comment, viewModel);
              },
              child: Image.asset(
                MagmaConstant.commentReport,
                width: 22.w,
                height: 22.w,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示评论详情对话框
  void _showCommentDetailDialog(
    BuildContext context,
    GatheringCommentModel comment,
    EventDetailNavigatorViewModel viewModel,
  ) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            width: 320.w,
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: MagmaColor.black,
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: MagmaColor.green, width: 1.w),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text('Comment Details').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w600,
                ),
                SizedBox(height: 16.h),
                // 评论内容
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: MagmaColor.green.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: MagmaColor.green, width: 1.w),
                  ),
                  child: Text(
                    comment.content,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w400,
                      height: 1.5,
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                // 按钮区域
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // 关闭按钮
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: MagmaColor.green.withValues(alpha: 0.2),
                          borderRadius: BorderRadius.circular(8.r),
                          border: Border.all(
                            color: MagmaColor.green,
                            width: 1.w,
                          ),
                        ),
                        child: Text(
                          'Close',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 显示举报对话框
  void _showReportDialog(
    BuildContext context,
    GatheringCommentModel comment,
    EventDetailNavigatorViewModel viewModel,
  ) {
    MagmaReportDialog.showReportDialog(
      context,
      title: 'Report Comment',
      subtitle: 'Please select a reason for reporting this comment',
      onReportSubmitted: (ReportOption option) {
        // 删除评论
        viewModel.deleteComment(comment.id);

        // 延迟触发滚动，确保评论删除后UI更新完成
        Future.delayed(Duration(milliseconds: 200), () {
          _triggerDifferentSpeedScroll();
        });

        // 显示成功提示
        MagmaToast.success(context, title: 'Comment reported and removed');
      },
    );
  }

  /// 让第二排滚动半条评论长度
  void _scrollSecondRowHalf() {
    // 延迟执行，确保UI完全加载
    Future.delayed(Duration(milliseconds: 500), () {
      if (_secondRowController.hasClients) {
        // 计算半条评论的长度：306.w + 12.w(margin) = 318.w，半条就是159.w
        final halfCommentWidth = 159.w;

        _secondRowController.animateTo(
          halfCommentWidth,
          duration: Duration(milliseconds: 800),
          curve: Curves.easeInOut,
        );
      } else {
        // 如果控制器未准备好，再次尝试
        Future.delayed(Duration(milliseconds: 500), () {
          _scrollSecondRowHalf();
        });
      }
    });
  }

  /// 触发不同速率的滚动
  void _triggerDifferentSpeedScroll() {
    // 延迟执行，确保UI更新完成
    Future.delayed(Duration(milliseconds: 100), () {
      if (_firstRowController.hasClients && _secondRowController.hasClients) {
        // 第一排滚动速率：慢
        _firstRowController.animateTo(
          _firstRowController.position.maxScrollExtent * 0.2,
          duration: Duration(milliseconds: 600),
          curve: Curves.easeInOut,
        );

        // 第二排滚动速率：快
        _secondRowController.animateTo(
          _secondRowController.position.maxScrollExtent * 0.4,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
  }
}

/// 虚线绘制器
class DashedLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = MagmaColor.black.withValues(alpha: 0.3)
          ..strokeWidth = 1.0
          ..style = PaintingStyle.stroke;

    const dashWidth = 6.0;
    const dashSpace = 6.0;
    double startX = 0;

    while (startX < size.width) {
      canvas.drawLine(
        Offset(startX, size.height / 2),
        Offset(startX + dashWidth, size.height / 2),
        paint,
      );
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

/// 处理编辑评论按钮点击
extension EventDetailStoryExtension on _EventDetailStoryState {
  /// 处理编辑评论按钮点击
  void _handleEditCommentTap(
    BuildContext context,
    EventDetailNavigatorViewModel viewModel,
  ) {
    // 检查用户是否登录
    if (!appState.userStore.isLoggedIn) {
      // 用户未登录，显示需要登录的弹窗
      LoginRequiredDialog.show(
        context,
        title: 'Login Required',
        message: 'Please log in to add a comment.',
        confirmText: 'Login',
        cancelText: 'Cancel',
      );
      return;
    }

    // 用户已登录，显示发送评论弹窗
    _showAddCommentDialog(context, viewModel);
  }

  /// 显示添加评论弹窗
  void _showAddCommentDialog(
    BuildContext context,
    EventDetailNavigatorViewModel viewModel,
  ) {
    final TextEditingController commentController = TextEditingController();

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            width: 320.w,
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: MagmaColor.black,
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: MagmaColor.green, width: 1.w),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text('Add Comment').blackHanSans(
                  fontSize: 20.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w600,
                ),
                SizedBox(height: 16.h),
                // 评论输入框
                Container(
                  decoration: BoxDecoration(
                    color: MagmaColor.green.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: MagmaColor.green, width: 1.w),
                  ),
                  child: TextField(
                    controller: commentController,
                    maxLines: 4,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w400,
                    ),
                    decoration: InputDecoration(
                      hintText: 'Write your comment...',
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: MagmaColor.white.withValues(alpha: 0.5),
                        fontWeight: FontWeight.w400,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(16.w),
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                // 按钮区域
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // 取消按钮
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: MagmaColor.green.withValues(alpha: 0.2),
                          borderRadius: BorderRadius.circular(8.r),
                          border: Border.all(
                            color: MagmaColor.green,
                            width: 1.w,
                          ),
                        ),
                        child: Text(
                          'Cancel',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: MagmaColor.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // 发送按钮
                    GestureDetector(
                      onTap: () {
                        final commentText = commentController.text.trim();
                        if (commentText.isNotEmpty) {
                          _addComment(context, viewModel, commentText);
                          Navigator.of(context).pop();
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: MagmaColor.green,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Text(
                          'Send',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: MagmaColor.black,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 添加评论
  void _addComment(
    BuildContext context,
    EventDetailNavigatorViewModel viewModel,
    String commentText,
  ) async {
    // 获取当前用户
    final currentUser = appState.userStore.currentUser;
    if (currentUser == null) return;

    // 使用GatheringOrganizer的submitGatheringComment方法
    final success = await appState.gatheringOrganizer.submitGatheringComment(
      viewModel.currentEvent?.id ?? '',
      currentUser.id,
      commentText,
    );

    if (success) {
      // 刷新评论列表
      viewModel._loadEventComments();
      viewModel.notifyListeners();

      // 显示成功提示
      MagmaToast.success(context, title: 'Comment added successfully');
    } else {
      // 显示错误提示
      MagmaToast.error(context, title: 'Failed to add comment');
    }
  }
}
